package cn.edu.scnu.semart.goods.controller;

import cn.edu.scnu.semart.model.goods.Goods;
import cn.edu.scnu.semart.goods.service.GoodsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品Controller
 */
@RestController
@RequestMapping("/goods")
//@CrossOrigin
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public Map<String, Object> searchGoods(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "desc") String sortOrder) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.searchGoods(page, keyword, categoryId, 
                                                             minPrice, maxPrice, sortBy, sortOrder);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 管理员搜索商品（返回所有审核状态的商品）
     */
    @GetMapping("/admin/search")
    public Map<String, Object> adminSearchGoods(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "desc") String sortOrder,
            @RequestParam(required = false) Integer auditStatus) {

        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.searchAllAuditStatusGoods(page, keyword, categoryId,
                    minPrice, maxPrice, sortBy,
                    sortOrder, auditStatus);

            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> getGoodsDetail(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Goods goods = goodsService.getGoodsDetail(id);
            if (goods != null) {
                result.put("success", true);
                result.put("data", goods);
            } else {
                result.put("success", false);
                result.put("message", "商品不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 根据用户ID获取商品列表
     */
    @GetMapping("/user/{userId}")
    public Map<String, Object> getGoodsByUserId(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getGoodsByUserId(userId, page);

            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 根据分类获取商品列表
     */
    @GetMapping("/category/{categoryId}")
    public Map<String, Object> getGoodsByCategory(
            @PathVariable Integer categoryId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getGoodsByCategory(categoryId, page);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取热门商品
     */
    @GetMapping("/hot")
    public Map<String, Object> getHotGoods(@RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Goods> hotGoods = goodsService.getHotGoods(limit);
            result.put("success", true);
            result.put("data", hotGoods);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取推荐商品
     */
    @GetMapping("/recommend")
    public Map<String, Object> getRecommendGoods(@RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Goods> recommendGoods = goodsService.getRecommendGoods(limit);
            result.put("success", true);
            result.put("data", recommendGoods);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 添加商品
     */
    @PostMapping("/add")
    public Map<String, Object> addGoods(@RequestBody Goods goods) {
        Map<String, Object> result = new HashMap<>();
        try {
            if(goods.getStatus() == null) goods.setStatus(3);
            boolean success = goodsService.save(goods);
            result.put("success", success);
            if (success) {
                result.put("message", "添加成功");
            } else {
                result.put("message", "添加失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 更新商品
     */
    @PutMapping("/update")
    public Map<String, Object> updateGoods(@RequestBody Goods goods) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = goodsService.updateById(goods);
            result.put("success", success);
            if (success) {
                result.put("message", "更新成功");
            } else {
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteGoods(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = goodsService.removeById(id);
            result.put("success", success);
            if (success) {
                result.put("message", "删除成功");
            } else {
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 直接审核通过商品
     */
    @PostMapping("/audit/approve/{goodsId}")
    public Map<String, Object> directApprove(
            @PathVariable Integer goodsId,
            @RequestParam Integer auditorId,
            @RequestParam String auditorName,
            @RequestParam(required = false) String remark) {

        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = goodsService.directApprove(goodsId, auditorId, auditorName, remark);
            result.put("success", success);
            if (success) {
                result.put("message", "审核通过成功");
            } else {
                result.put("message", "审核通过失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 直接审核拒绝商品
     */
    @PostMapping("/audit/reject/{goodsId}")
    public Map<String, Object> directReject(
            @PathVariable Integer goodsId,
            @RequestParam Integer auditorId,
            @RequestParam String auditorName,
            @RequestParam String rejectReason) {

        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = goodsService.directReject(goodsId, auditorId, auditorName, rejectReason);
            result.put("success", success);
            if (success) {
                result.put("message", "审核拒绝成功");
            } else {
                result.put("message", "审核拒绝失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取待审核商品列表
     */
    @GetMapping("/audit/pending")
    public Map<String, Object> getPendingAuditGoods(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getPendingAuditGoods(page);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取已审核商品列表
     */
    @GetMapping("/audit/approved")
    public Map<String, Object> getAuditedGoods(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getAuditedGoods(page);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取审核拒绝的商品列表
     */
    @GetMapping("/audit/rejected")
    public Map<String, Object> getRejectedGoods(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getRejectedGoods(page);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 根据审核状态获取商品列表
     */
    @GetMapping("/audit/status/{auditStatus}")
    public Map<String, Object> getGoodsByAuditStatus(
            @PathVariable Integer auditStatus,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Goods> page = new Page<>(current, size);
            IPage<Goods> goodsPage = goodsService.getGoodsByAuditStatus(auditStatus, page);
            
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 批量获取获取商品列表
     */
    @PostMapping("/batch")
    public List<Goods> getBatchByIds(@RequestBody List<Integer> ids) {
        return goodsService.getBatchByIds(ids);
    }

    /**
     * 扣减库存
     */
    @PostMapping("/deduct-stock")
    public Boolean deductStock(@RequestBody Map<Integer, Integer> deductMap) {
        return goodsService.deductStock(deductMap);
    }

    /**
     * 恢复库存
     */
    @PostMapping("/restore-stock")
    public Boolean restoreStock(@RequestBody Map<Integer, Integer> restoreMap) {
        return goodsService.restoreStock(restoreMap);
    }

    @GetMapping({"/user/audit/pending"})
    public Map<String, Object> getUserPendingAuditGoods(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, @RequestParam Integer userId) {
        Map<String, Object> result = new HashMap();

        try {
            Page<Goods> page = new Page((long)current, (long)size);
            IPage<Goods> goodsPage = this.goodsService.getUserPendingAuditGoods(page, userId);
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception var7) {
            result.put("success", false);
            result.put("message", var7.getMessage());
        }

        return result;
    }

    @GetMapping({"/user/audit/approved"})
    public Map<String, Object> getUserAuditedGoods(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, @RequestParam Integer userId) {
        Map<String, Object> result = new HashMap();

        try {
            Page<Goods> page = new Page((long)current, (long)size);
            IPage<Goods> goodsPage = this.goodsService.getUserAuditedGoods(page, userId);
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception var7) {
            result.put("success", false);
            result.put("message", var7.getMessage());
        }

        return result;
    }

    @GetMapping({"/user/audit/rejected"})
    public Map<String, Object> getUserRejectedGoods(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, @RequestParam Integer userId) {
        Map<String, Object> result = new HashMap();

        try {
            Page<Goods> page = new Page((long)current, (long)size);
            IPage<Goods> goodsPage = this.goodsService.getUserRejectedGoods(page, userId);
            result.put("success", true);
            result.put("data", goodsPage);
        } catch (Exception var7) {
            result.put("success", false);
            result.put("message", var7.getMessage());
        }

        return result;
    }
} 